<script setup lang="ts">
// 发布文章组件的逻辑将在这里实现
import { getArticleDetailInfoAPI, publishArticleAPI, uploadImageAPI } from '@/api/publish'
import type { channel } from '@/types/article'
import type { PublishArticleParams } from '@/types/publish'
import {
  ElMessage,
  type FormInstance,
  type UploadFile,
  type UploadFiles,
  type UploadInstance,
  type UploadRequestOptions,
  type UploadUserFile,
} from 'element-plus'
import { onMounted, ref, shallowRef } from 'vue'

import { Plus } from '@element-plus/icons-vue'
import type { IDomEditor } from '@wangeditor/editor'
import { useRouter } from 'vue-router'

// 频道列表
const channelList = ref<channel[]>([])

// 表单数据
const publishArticleParams = ref<PublishArticleParams>({
  title: '', // 标题
  id: '', // 文章id
  content: '', // 富文本编辑器
  cover: {
    type: 1, // 封面类型
    images: [], // 封面图片
    uid: [], // 封面图片的uid
  },
  channel_id: undefined, // 频道id
})



const fileList = ref<UploadUserFile[]>([])
const showUpload = ref(true)
const uploadRef = ref<UploadInstance>()

//上传图片
const uploadImage = async (options: UploadRequestOptions) => {
  publishArticleParams.value.cover.uid?.push(options.file.uid)
  const formData = new FormData()
  formData.append('image', options.file)
  const {
    data: { url },
  } = await uploadImageAPI(formData)
  publishArticleParams.value.cover.images.push(url)
}

/** 封面类型切换 */
const changeCoverType = (value: string | number | boolean | undefined) => {
  uploadRef.value?.clearFiles()
  showUpload.value = true
  publishArticleParams.value.cover.images = []
  publishArticleParams.value.cover.uid = []
}

/** 文章数超出限制 */
const handleUpload = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  if (uploadFiles.length === publishArticleParams.value.cover.type) {
    showUpload.value = false
  } else {
    showUpload.value = true
  }
}

/** 移除图片方法 */
const removeImage = (file: UploadFile, uploadFiles: UploadFiles) => {
  const index = publishArticleParams.value.cover.uid?.indexOf(file.uid)
  if (index === undefined) return
  publishArticleParams.value.cover.images.splice(index, 1)
  publishArticleParams.value.cover.uid?.splice(index, 1)
  if (uploadFiles.length === publishArticleParams.value.cover.type) {
    showUpload.value = false
  } else {
    showUpload.value = true
  }
}

//非空校验
const rules = {
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { min: 1, max: 30, message: '长度在 1 到 30 个字符', trigger: 'blur' },
  ],
  channel_id: [{ required: true, message: '请选择频道', trigger: 'change' }],
  cover: [{ required: true, message: '请上传封面', trigger: ' change' }],
  content: [{ required: true, message: '请输入文章内容', trigger: 'blur' }],
}

/** 记录 editor 实例，重要！ */
const editorRef = shallowRef()
const handleCreated = (editor: IDomEditor) => {
  editorRef.value = editor
}

//路由
const router = useRouter()

//表单ref
const formRef = ref<FormInstance>()

//存入草稿
const saveDraft = async () => {
  try {
    await formRef.value?.validate()
    const res = await publishArticleAPI(true, publishArticleParams.value)
    ElMessage.success('存入草稿成功')
    router.push('/article')
    console.log(res)
  } catch (error) {
    console.log(error)
  }
}

//发布文章
const publishArticle = async () => {
  try {
    await formRef.value?.validate()
    const res = await publishArticleAPI(false, publishArticleParams.value)
    ElMessage.success('发布成功')
    router.push('/article')
    console.log(res)
  } catch (error) {
    console.log(error)
  }
}

//获取文章id
const getArticleId = () => {
  const id = router.currentRoute.value.query.id
  if (id) {
    publishArticleParams.value.id = id as string
  }
}

onMounted(() => {
  getArticleId()
})

//获取文章详情
const getArticleDetail = async () => {
  const res = await getArticleDetailInfoAPI(publishArticleParams.value.id)
  publishArticleParams.value.title = res.data.title
  publishArticleParams.value.channel_id = res.data.channel_id
  publishArticleParams.value.content = res.data.content
}

onMounted(() => {
  getArticleDetail()
})




</script>

<template>
  <el-card shadow="always">
    <!-- 头部：面包屑 -->
    <template #header>
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item to="/">首页</el-breadcrumb-item>
        <!-- 编辑文章 -->
        <el-breadcrumb-item>{{ publishArticleParams.id ? '编辑文章' : '发布文章' }}</el-breadcrumb-item>
      </el-breadcrumb>
    </template>

    <!-- 主体：表单 -->
    <el-form label-width="120px" :model="publishArticleParams" :rules="rules" ref="formRef">
      <el-form-item label="标题：" prop="title">
        <el-input
          v-model="publishArticleParams.title"
          placeholder="请输入文章标题"
          style="width: 400px"
        ></el-input>
      </el-form-item>

      <el-form-item label="频道：" prop="channel_id"  >
        <el-select v-model="publishArticleParams.channel_id"  placeholder="请选择频道" clearable  >
          <el-option
            v-for="item in channelList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="封面：" prop="cover">
        <el-radio-group v-model="publishArticleParams.cover.type" @change="changeCoverType">
          <el-radio :label="1">单图</el-radio>
          <el-radio :label="3">三图</el-radio>
          <el-radio :label="0">无图</el-radio>
          <el-radio :label="-1">自动</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item>
        <div v-if="publishArticleParams.cover.type === 1 || publishArticleParams.cover.type === 3">
          <el-upload
            :limit="publishArticleParams.cover.type"
            action=""
            list-type="picture-card"
            ref="uploadRef"
            :http-request="uploadImage"
            :on-change="handleUpload"
            :on-remove="removeImage"
            v-model:file-list="fileList"
          >
            <template #default>
              <div v-if="showUpload">
                <el-icon><Plus /></el-icon>
              </div>
              <el-button v-else type="danger" disabled>上传已达限制</el-button>
            </template>
          </el-upload>
        </div>
      </el-form-item>

      <el-form-item label="内容：" prop="content">
        <el-input
          v-model="publishArticleParams.content"
          style="width: 240px"
          :rows="2"
          type="textarea"
          placeholder="请输入文章内容"
          @onCreated="handleCreated"
        />
      </el-form-item>

      <el-form-item label=""  >
        <el-button type="primary" @click="publishArticle">{{ publishArticleParams.id ? '更新文章' : '发表文章' }}</el-button>
        <el-button @click="saveDraft">存入草稿</el-button>
      </el-form-item>
      {{ publishArticleParams.id }}
    </el-form>
  </el-card>
</template>

<style scoped lang="less"></style>
